package com.meiji.toutiao.module.news;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.meiji.toutiao.Constant;
import com.meiji.toutiao.R;
import com.meiji.toutiao.adapter.base.BasePagerAdapter;
import com.meiji.toutiao.bean.news.NewsChannelBean;
import com.meiji.toutiao.database.dao.NewsChannelDao;
import com.meiji.toutiao.module.base.BaseListFragment;
import com.meiji.toutiao.module.news.article.NewsArticleView;
import com.meiji.toutiao.module.news.channel.NewsChannelActivity;
import com.meiji.toutiao.module.wenda.article.WendaArticleView;
import com.meiji.toutiao.util.RxBus;
import com.meiji.toutiao.util.SettingUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;

/**
 * Created by Meiji on 2016/12/12.
 * 功能：新闻界面的fragment
 */

public class NewsTabLayout extends Fragment {

	public static final String TAG = "NewsTabLayout";
	private static NewsTabLayout instance = null;
	private ViewPager viewPager;
	private BasePagerAdapter adapter;
	private LinearLayout linearLayout;
	private NewsChannelDao dao = new NewsChannelDao();
	private List<Fragment> fragmentList;           // 存放fragment的list
	private List<String> titleList;
	private Observable<Boolean> observable;
	private Map<String, Fragment> map = new HashMap<>();

	/**
	 * 初始化构造函数方法
	 * @return
	 */
	public static NewsTabLayout getInstance() {
		if (instance == null) {
			instance = new NewsTabLayout();
		}
		return instance;
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_news_tab, container, false);
		initView(view);
		initData();
		return view;
	}

	@Override
	public void onResume() {
		super.onResume();
		linearLayout.setBackgroundColor(SettingUtil.getInstance().getColor());
	}

	/**
	 * 功能：相应布局的id,和相关的设置
	 *
	 * @param view
	 */
	private void initView(View view) {

		TabLayout tab_layout = view.findViewById(R.id.tab_layout_news);  // tablayout布局
		viewPager = view.findViewById(R.id.view_pager_news);            // viewpager布局

		tab_layout.setupWithViewPager(viewPager);            // tablayout和viewpager关联联动起来
		tab_layout.setTabMode(TabLayout.MODE_SCROLLABLE); // 设置tablayout可以滑动

		ImageView add_channel_iv = view.findViewById(R.id.add_channel_iv);  // tablayout 右面管理的"+"号:
		add_channel_iv.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				NewsTabLayout.this.startActivity(new Intent(NewsTabLayout.this.getActivity(), NewsChannelActivity.class));
			}
		});  // “+”点击跳转到新界面

		linearLayout = view.findViewById(R.id.header_layout);       // tablayout 哪行的外面的Linearlayout布局
		linearLayout.setBackgroundColor(SettingUtil.getInstance().getColor());     //  设置器相应的颜色
	}

	/**
	 * 功能：填充数据
	 */
	private void initData() {
		initTabs();
		adapter = new BasePagerAdapter(getChildFragmentManager(), fragmentList, titleList);  // viewpager的填充
		viewPager.setAdapter(adapter);
		viewPager.setOffscreenPageLimit(15);  // 预加载 15页

		observable = RxBus.getInstance().register(NewsTabLayout.TAG);
		observable.subscribe(new Consumer<Boolean>() {
			@Override
			public void accept(Boolean isRefresh) throws Exception {
				if (isRefresh) {
					NewsTabLayout.this.initTabs();
					adapter.recreateItems(fragmentList, titleList);   // 更新fragment和tittleList列表
				}
			}
		});
	}

	/**
	 * tablayout 上显示的标题，其数据在数据库中查找
	 */
	private void initTabs() {
		List<NewsChannelBean> channelList = dao.query(1);  // 在数据库中查找标示为1的数据
		fragmentList = new ArrayList<>();   // 初始化存放fragment的list
		titleList = new ArrayList<>();   // tablayout标题数列

		if (channelList.size() == 0) {  // 如果数据库中产询出来的数据为空
			dao.addInitData();              // 作为将所有的tittle设置到数据库中
			channelList = dao.query(Constant.NEWS_CHANNEL_ENABLE);  // 在数据库中查询，标示是1的，也就是可以显示的tittle数据
		}

		for (NewsChannelBean bean : channelList) {  // 遍历获取的标示为1的数据的对象

			Fragment fragment = null;
			String channelId = bean.getChannelId();   // 获取查询出来设置标示为1的，要显示的tittle数据，的ID

			switch (channelId) {
				case "question_and_answer":
					if (map.containsKey(channelId)) {
						fragmentList.add(map.get(channelId));
					} else {
						fragment = WendaArticleView.newInstance();  // 获取fragment对象，——————
						fragmentList.add(fragment);  // 将对象添加到list
					}

					break;
				default:
					if (map.containsKey(channelId)) {
						fragmentList.add(map.get(channelId));
					} else {
						fragment = NewsArticleView.newInstance(channelId);
						fragmentList.add(fragment);
					}
					break;
			}

			titleList.add(bean.getChannelName());    // 将tablayout名称放到list中去

			if (fragment != null) {
				map.put(channelId, fragment);
			}
		}
	}

	public void onDoubleClick() {
		if (titleList != null && titleList.size() > 0 && fragmentList != null && fragmentList.size() > 0) {
			int item = viewPager.getCurrentItem();
			((BaseListFragment) fragmentList.get(item)).onRefresh();
		}
	}

	@Override
	public void onDestroy() {
		RxBus.getInstance().unregister(NewsTabLayout.TAG, observable);
		if (instance != null) {
			instance = null;
		}
		super.onDestroy();
	}
}
